<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 登陆
 */
declare (strict_types=1);

namespace app\backend\controller;

use app\backend\validate\LoginValidate;
use app\BaseController;
use app\extend\model\Admin;
use app\extend\model\Role;
use think\facade\View;

class Login extends BaseController
{
    /**
     * 登陆
     */
    public function index()
    {
        if (request()->isPost()) {
            $validate = new LoginValidate();
            $ret = $validate->scene('index')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $account = input('account','');
            $password = input('password','');
            $code = input('code','');

            if (!captcha_check($code)) {
                return json(_E('验证码错误'));
            }

            $adminInfo = Admin::where([
                ['account','=',$account]
            ])->field('id,nickname,password,salt,role_id,status,role_id')->find();

            if (empty($adminInfo) || $adminInfo->password != password($password, $adminInfo->salt)) {
                return json(_E('用户名或密码输入错误'));
            }

            if($adminInfo->status == 0){
                return json(_E('用户状态不可用'));
            }

            //判断角色状态是否可用
            $roleInfo = Role::where([
                ['id','=',$adminInfo->role_id]
            ])->field('id,status')->find();
            if($roleInfo->status == 0){
                return json(_E('角色状态不可用'));
            }

            session('uid',$adminInfo->id);
            session('nickname',$adminInfo->nickname);
            session('role_id',$adminInfo->role_id);

            return json(_S('登录成功'));
        } else {
            View::engine()->layout(false);
            return view('index');
        }
    }

    /**
     * 退出
     */
    public function logout()
    {
        session(null);
        return redirect('Index');
    }
}
